import cv2
import numpy as np

img = cv2.imread('1.jpg', cv2.IMREAD_GRAYSCALE)
ret,thresh1 = cv2.threshold(img, 127, 255, cv2.THRESH_BINARY)
cv2.imshow('img',img)
cv2.imshow('thresh1',thresh1)
kernel = np.ones((3,3), np.uint8)
##开运算 先腐蚀 在膨胀
morphologyEx_open = cv2.morphologyEx(thresh1,cv2.MORPH_OPEN, kernel)
cv2.imshow('morphologyEx_open',morphologyEx_open)
##闭运算 先膨胀再腐蚀
morphologyEx_close = cv2.morphologyEx(thresh1,cv2.MORPH_CLOSE, kernel)
cv2.imshow('morphologyEx_close',morphologyEx_close)
cv2.waitKey(0)
cv2.destroyAllWindows()